var page = require('webpage').create(), resultLink;
phantom.injectJs("../jquery.js");
page.open('https://www.baidu.com', function(status) {
	if(status == "success") {
		var m = 0;
		console.log('open first success');
		page.evaluate(function(text) {
			$("#kw").val(text);
			var ev = document.createEvent("MouseEvent");
			ev.initMouseEvent(
		        "click",
		        true /* bubble */, true /* cancelable */,
		        window, null,
		        0, 0, 0, 0, /* coordinates */
		        false, false, false, false, /* modifier keys */
		        0 /*left*/, null
		    );
		    document.getElementById("su").dispatchEvent(ev);
		}, "高考妙计");
		page.onPageCreated = function(newPage) {
			console.log("create a new page");
			var urlArray = [], index = 0;
			newPage.onLoadStarted  = function() {
//				setTimeout(function() {
//					var splitUrl;
//					var imgUrl = newPage.evaluate(function() {
//						return window.location.href;
//					})
//					if(imgUrl == 'about:blank') {
////						setTimeout(function() {
////							console.log('title'+ newPage.title)
////							console.log("use page url  " + newPage.url);
////							newPage.close();
////						},3000)
//					}else {
////						console.log('title'+ newPage.title);
////						console.log("use page url  " + newPage.url);
//						newPage.close();
//					}
//				}, 3000);
			}
		}
		var link_length;
		setTimeout(function() {
			page.render("my.png");
		}, 2000);
		
		for(var i = 0; i < 10; i++) {
			page.evaluate(function(index) {
				function ele_click(el) {
					var ev = document.createEvent("MouseEvent");
					ev.initMouseEvent(
				        "click",
				        true /* bubble */, true /* cancelable */,
				        window, null,
				        0, 0, 0, 0, /* coordinates */
				        false, false, false, false, /* modifier keys */
				        0 /*left*/, null
				    );
				    el.dispatchEvent(ev);
				}
				setTimeout(function() {
					var a = document.querySelectorAll("#content_left .c-container h3 a")[index];
					ele_click(a);
				}, 3000);
			}, i);
		}
	}
})
page.onResourceReceived = function(response) {
	console.log('Response (#' + response.id + ', stage' + response.stage + '): ' + JSON.stringify(response));
	
}
 